# -*- encoding: utf-8 -*-

# here put the import utils
# -*- encoding: utf-8 -*-

import os
import inspect
from datetime import datetime
from loguru import logger
from config.path import LOG_DIR


class Log:
    """输出日志到文件和控制台"""

    def __init__(self):
        # 文件的命名
        log_name = f"test_{datetime.now().strftime('%Y_%m_%d_%H%M%S')}.log"
        log_path = os.path.join(LOG_DIR, log_name)
        # 判断日志文件夹是否存在，不存则创建
        if not os.path.exists(LOG_DIR):
            os.mkdir(LOG_DIR)
        # 日志输出格式
        # formatter = "{time:YYYY-MM-DD HH:mm:ss} | {level}: {message}"
        formatter = "{time:YYYY-MM-DD HH:mm:ss} | {level} | {name}.{function}: {message}"

        # 日志写入文件
        logger.add(
            log_path,  # 写入目录指定文件
            format=formatter,
            encoding="utf-8",
            level='DEBUG',
            retention="7 days",  # 设置历史保留时长
            rotation="10 MB",  # 切割，设置文件大小
            # enqueue=True  # 异步写入
            # compression="zip"   # 文件压缩
        )

    @staticmethod
    def debug(msg):
        # logger.debug(msg)
        frame = inspect.currentframe().f_back  # 获取调用者的帧对象
        module_name = frame.f_globals['__name__']  # 获取模块名
        function_name = frame.f_code.co_name  # 获取函数名
        logger.debug(f"{module_name}.{function_name}: {msg}")

    @staticmethod
    def info(msg):
        # logger.info(msg)
        frame = inspect.currentframe().f_back  # 获取调用者的帧对象
        module_name = frame.f_globals['__name__']  # 获取模块名
        function_name = frame.f_code.co_name  # 获取函数名
        logger.info(f"{module_name}.{function_name}: {msg}")

    @staticmethod
    def warning(msg):
        # logger.warning(msg)
        frame = inspect.currentframe().f_back  # 获取调用者的帧对象
        module_name = frame.f_globals['__name__']  # 获取模块名
        function_name = frame.f_code.co_name  # 获取函数名
        logger.warning(f"{module_name}.{function_name}: {msg}")

    @staticmethod
    def error(msg):
        # logger.error(msg)
        frame = inspect.currentframe().f_back  # 获取调用者的帧对象
        module_name = frame.f_globals['__name__']  # 获取模块名
        function_name = frame.f_code.co_name  # 获取函数名
        logger.error(f"{module_name}.{function_name}: {msg}")

    @staticmethod
    def exception(msg):
        # logger.exception(msg)
        frame = inspect.currentframe().f_back  # 获取调用者的帧对象
        module_name = frame.f_globals['__name__']  # 获取模块名
        function_name = frame.f_code.co_name  # 获取函数名
        logger.exception(f"{module_name}.{function_name}: {msg}")

    @staticmethod
    def trace(msg):
        # logger.trace(msg)
        frame = inspect.currentframe().f_back  # 获取调用者的帧对象
        module_name = frame.f_globals['__name__']  # 获取模块名
        function_name = frame.f_code.co_name  # 获取函数名
        logger.trace(f"{module_name}.{function_name}: {msg}")


log = Log()
